package org.chen.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class BatchAsyncConfig {

    @Value("${task.execution.pool.core-size:32}")
    private int corePoolSize;

    @Value("${task.execution.pool.max-size:64}")
    private int maxPoolSize;

    @Value("${task.execution.pool.queue-capacity:500}")
    private int queueCapacity;

    @Bean("batchTaskExecutor")
    public AsyncTaskExecutor batchTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);  // 核心线程数
        executor.setMaxPoolSize(maxPoolSize);   // 最大线程数
        executor.setQueueCapacity(queueCapacity); // 增加队列容量
        executor.setThreadNamePrefix("batch-async-");
        // 增加线程空闲时间，允许及时释放资源
        executor.setKeepAliveSeconds(60);
        // 允许核心线程超时，不活跃时释放
        executor.setAllowCoreThreadTimeOut(true);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 添加拒绝策略
        executor.initialize();
        return executor;
    }
}